package com.gzs.space.utils;

import org.csource.common.NameValuePair;
import org.csource.fastdfs.*;

import java.io.InputStream;

/**
 * @author GZS
 * @date 2022年04月09日
 */
public class FastDFSUtils {
	//初始化客户端对象
	//存储器客户端对象。文件上传下载，是保存在存储器中的。
	private final static StorageClient storageClient;

	static {
		try {
			//给GlobalClient类型中的静态属性g_tracker_group赋值
			//加载配置文件
			// InputStream inputStream = FastDFSUtils.class.getClassLoader()
			// 		.getResourceAsStream("fdfs.properties");
			// Properties properties = new Properties();
			// properties.load(inputStream);

			ClientGlobal.initByProperties("fdfs.properties");
			//找跟踪器
			//跟踪器客户端
			TrackerClient trackerClient = new TrackerClient();
			TrackerServer trackerServer = trackerClient.getConnection();
			StorageServer storageServer = trackerClient.getStoreStorage(trackerServer);

			storageClient = new StorageClient(trackerServer,storageServer);
		} catch (Exception e) {
			e.printStackTrace();
			throw new ExceptionInInitializerError(e);
		}
	}

	/**
	 * 上传文件到fastdfs
	 * @param inputStream
	 * @param originalFileName 文件上传原始名
	 * @return
	 */
	public static String[] upload(InputStream inputStream,String originalFileName){
		try {
			// 获取文件大小
			int size = inputStream.available();
			byte[] tmp = new byte[size];
			//读取文件全部内容到字节数组
			inputStream.read(tmp,0,size);

			// 准备文件元数据
			NameValuePair[] nameValuePairs = new NameValuePair[]{
					new NameValuePair("fileName",originalFileName),
					new NameValuePair("size",size+""),
					new NameValuePair("createTime",System.currentTimeMillis()+"")
			};
			// 上传文件,返回一个字符串，长度是2。
			// 0下标是存储器的卷名
			// 1下标是存储器自动生成的文件名（包括文件夹）
			String[] result = storageClient.upload_file(tmp, originalFileName.substring(originalFileName.lastIndexOf(".")+1), nameValuePairs);
			return result;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 *  删除文件
	 * @param groupName
	 * @param newFileName
	 * @return
	 */
	public static boolean delete(String groupName,String newFileName){
		try {
			int resultCode = storageClient.delete_file(groupName,newFileName);
			return resultCode == 0;
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}


	/**
	 * 下载文件
	 * @return
	 */
	public static byte[] downLoad(String groupName,String newFileName){
		try {
			//查询文件的元数据
			//NameValuePair[] valuePairs = storageClient.get_metadata(groupName, newFileName);

			return storageClient.download_file(groupName,newFileName);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
}
